/*
    有平均刻度的拖动条
    by chenzhian
*/

(function ($, window, undefined) {
    function drawbar(obj, breakCount, aEchoData, outputContainer) {
        this.$obj = $(obj);
        this.outputContainer = outputContainer;
        this.breakCount = breakCount;
        this.aEchoData = aEchoData;
        this.startX;
        this.handlerPos;
        this.nowX = 0;
        this.nowPos = 0;
        this.stickWidth = obj.offsetWidth;
        this.drawFrocusStop = false;
        //$("#t1").html(this.stickWidth)
        //$("#t2").html($("#handler2")[0].offsetWidth)
        // Simple way to check if some form of pointerevents is enabled or not
        if (window.PointerEventsSupport === undefined) {
            window.PointerEventsSupport = false;
            if (window.PointerEvent || window.navigator.msPointerEnabled) {
                window.PointerEventsSupport = true;
            }
        }

        // Shim for requestAnimationFrame from Paul Irishpaul ir
        // http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
        this.requestAnimFrame = (function () {
            return window.requestAnimationFrame ||
                    window.webkitRequestAnimationFrame ||
                    window.mozRequestAnimationFrame ||
                    function (callback) {
                        window.setTimeout(callback, 1000 / 60);
                    };
        })().bind(window);

        //触控触发
        this.eTouchstart = function (e) {
            //去除父容器的事件
            e.stopPropagation();
            this.drawFrocusStop = false;
            if (window.PointerEventsSupport) {
                document.addEventListener(pointerMoveName, this.eTouchmove, true);
                document.addEventListener(pointerUpName, this.eTouchEnd, true);
            } else {
                document.addEventListener('touchmove', this.eTouchmove, true);
                document.addEventListener('touchend', this.eTouchEnd, true);
                document.addEventListener('touchcancel', this.eTouchEnd, true);
                document.addEventListener('mousemove', this.eTouchmove, true);
                document.addEventListener('mouseup', this.eTouchEnd, true);
            }
            var oTouch = e.touches ? e.touches[0] : e;
            this.touchStart(oTouch);
        }.bind(this);

        //触控移动
        this.eTouchmove = function (e) {
            var oTouch = e.touches ? e.touches[0] : e;
            var that = this;
            //this.requestAnimFrame(function () {
            //    that.touchMove(oTouch);
            //});
            //requestAnimFrame反而会lag
            that.touchMove(oTouch);
        }.bind(this);

        //触控结束
        this.eTouchEnd = function (e) {
            this.drawFrocusStop = true;
            if (window.PointerEventsSupport) {
                document.removeEventListener(pointerMoveName, this.eTouchmove, true);
                document.removeEventListener(pointerUpName, this.eTouchmove, true);
            } else {
                document.removeEventListener('touchmove', this.eTouchmove, true);
                document.removeEventListener('touchend', this.eTouchEnd, true);
                document.removeEventListener('touchcancel', this.eTouchEnd, true);
                document.removeEventListener('mousemove', this.eTouchmove, true);
                document.removeEventListener('mouseup', this.eTouchEnd, true);
            }
            this.touchEnd();
        }.bind(this);
        //----init:----//
        //event bind:


        if (window.PointerEventsSupport) {
            //Pointer Event Listeners
            obj.addEventListener(pointerDownName, this.eTouchstart, false);

        } else {
            //Touch Listeners
            obj.addEventListener('touchstart', this.eTouchstart, false);
            //Mouse Listeners
            obj.addEventListener('mousedown', this.eTouchstart, false);
        }
    }

    drawbar.prototype = {
        touchStart: function (oTouch) {
            this.startX = oTouch.clientX;
            var str = this.$obj.css("transform") || this.$obj.css("-webkit-transform") || this.$obj.css("-moz-transform");
            this.handlerPos = this.getXNumFromMatrix(str);
        },
        touchMove: function (oTouch) {
            var nowX = oTouch.clientX;
            var dis = nowX - this.startX;
            var newPos = this.handlerPos + dis;
            var actValue;
            if (newPos > this.stickWidth || newPos < 0) { return; }
            //假如已经触发touch end:
            if (this.drawFrocusStop) {return;}
            actValue = "matrix(1, 0, 0, 1, " + newPos + ", 0)";
            this.$obj.css({
                '-webkit-transform': actValue,
                '-moz-transform': actValue
            });
            this.nowPos = newPos;

        },
        touchEnd: function () {
            
            var nowPos = this.nowPos,
                stickWidth = this.stickWidth;
            nowPos = nowPos < 0 ? 0 : nowPos;
            nowPos = nowPos > stickWidth ? stickWidth : nowPos;
            //每段长度
            var breakWidth = stickWidth / this.breakCount;
            //handler已到达的刻度
            var level = parseInt(nowPos / breakWidth);
            //进一
            if (nowPos % breakWidth - breakWidth / 3 > 0) {
                ++level;
            }
            nowPos = level * breakWidth;

            var actValue = "matrix(1, 0, 0, 1, " + nowPos + ", 0)";
            this.$obj.css({
                '-webkit-transform': actValue,
                '-moz-transform': actValue
            });
            //frocus reflow
            this.$obj.find("*")[0].offsetWidth;
            this.echoData(level);
        },
        echoData: function (level) {
            var $cont = $(this.outputContainer);
            $cont.val(this.aEchoData[level]);
            $cont.trigger("change");
        },
        getXNumFromTrans3d: function (str) {
            var val = str.match(/3d\((\d+)\%/);
            if (val === null) { return null; }
            return parseInt(val[1]);
        },
        //获取其他参数固定时的X参数(写死)
        getXNumFromMatrix: function (str) {
            var val = str.match(/1\, 0\, 0\, 1\, (.+)\, 0\)/);
            if (val === null) { return null; }
            return parseInt(val[1]);
        }
    }

    extMylib(window.mylib, "drawbar", drawbar);
}(Zepto, window, undefined));



Zepto(function ($) {
    $("[data-role=drawbar]").find(".drawHandler").each(function (i, item) {
        var echoContainer = $(item).data("echo");
        var breaker = $(item).data("break");
        var $breakerSet = $(breaker).children();
        var len = $(breaker).children().length - 1;
        var aData = [];
        $breakerSet.each(function (i2, item2) {
            var breakNum = $(item2).find("span").html();
            aData.push(breakNum);
        })
        new window.mylib.drawbar(item, len, aData, echoContainer);
    });
    

});

